import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { Component, Input } from '@angular/core';
import { CascaderItem } from 'ng-devui';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
@Component({
  selector: 'app-edit-store-house',
  templateUrl: './edit-store-house.component.html',
  styleUrls: ['./edit-store-house.component.scss']
})
export class EditStoreHouseComponent {
  @Input() data: any;
  options :any;//部门
  stroehouse ={
    warehouseName: '',
    warehouseCategoryId: null,
    isEnabled: false,
    isNegative: false,
    qrCode: '',
  };//编辑仓库
  warehouseNum:any;
  items:any[]=[
    '启用', '禁用'
  ];
  pathPids:any[]=[];
  currentSelectedItem = '启用';
  constructor(private StorehouseService:StorehouseService) { }
  ngOnInit(): void {
    this.StorehouseService.getWarehouseById(this.data.id).subscribe((res:any)=>{
      this.stroehouse.warehouseName = res.warehouseName
      this.stroehouse.qrCode = res.qrCode
      this.warehouseNum = res.warehouseNum
      this.stroehouse.isNegative = res.isNegative
      this.stroehouse.isEnabled = res.isEnabled
      this.currentSelectedItem = this.stroehouse.isEnabled == true ? '启用' : '禁用'
      this.stroehouse.warehouseCategoryId = res.warehouseCategoryId
      for(let node of  this.data.options){
        const path = this.getPathPids(node, this.stroehouse.warehouseCategoryId);
          this.pathPids = path;
          if (path) {
            break;
          }
      }
    })
    this.stroehouse.isEnabled = this.currentSelectedItem == '启用' ? true : false
    this.options = this.convertToCascaderItem(this.data.options)
  }
  convertToCascaderItem(data: any[]): CascaderItem[]{
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.warehouseCategoryName,
        value: item.warehouseCategoryId,
      };
      if (item.subWarehouseCategories) {
        cascaderItem.children = this.convertToCascaderItem(item.subWarehouseCategories);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  onChanges($event: string | any[]){
    this.stroehouse.warehouseCategoryId = $event[$event.length-1]
  }
  valueChange(value: string): void {
    this.stroehouse.isEnabled = value == '启用' ? true : false
  }
  getPathPids(node: any, targetId: any, path = []) {
    if (node.warehouseCategoryId === targetId) {
      return [...path, node.warehouseCategoryId];
    }
    if (node.subWarehouseCategories) {
      for (let subNode of node.subWarehouseCategories) {
        const subPath = this.getPathPids(subNode, targetId, [...path, node.warehouseCategoryId]);
        if (subPath) {
          return subPath;
        }
      }
    }
    return null;
  } //获取树形菜单pid的路
}
